package com.xxtx.trade.sysUser.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xxtx.trade.common.util.IdCreateUtil;
import com.xxtx.trade.common.util.model.PageInfo;
import com.xxtx.trade.common.util.model.Result;
import com.xxtx.trade.sysUser.bean.TradeRoleMenu;
import com.xxtx.trade.sysUser.bean.TradeSysMenu;
import com.xxtx.trade.sysUser.bean.TradeSysRole;
import com.xxtx.trade.sysUser.dto.TradeSysRoleDto;
import com.xxtx.trade.sysUser.mapper.TradeRoleMenuMapper;
import com.xxtx.trade.sysUser.mapper.TradeSysMenuMapper;
import com.xxtx.trade.sysUser.mapper.TradeSysRoleMapper;
import com.xxtx.trade.sysUser.service.TradeSysRoleService;
import com.xxtx.trade.sysUser.vo.TradeSysRoleVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@Service
public class TradeSysRoleServiceImpl implements TradeSysRoleService {
    private static final Logger LOGGER = LoggerFactory.getLogger(TradeSysMenuServiceImpl.class);
    @Autowired
    private TradeSysRoleMapper tradeSysRoleMapper;
    @Autowired
    private TradeRoleMenuMapper tradeRoleMenuMapper;
    @Autowired
    private TradeSysMenuMapper tradeSysMenuMapper;
     /**
     * 查询角色列表
     * @param tradeSysRoleDto
     * @return
     */
    @Override
    public Result roleList(TradeSysRoleDto tradeSysRoleDto) {
        Result<Object> result = new Result<>();
        try {
            Page<Object> page = PageHelper.startPage(tradeSysRoleDto.getPageNo(), tradeSysRoleDto.getPerPageNum(), "createTime DESC");
            List<TradeSysRoleVo> list=tradeSysRoleMapper.selectQueryList(tradeSysRoleDto);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(list);
            result.setData(pageInfo);
        }catch (Exception e){
            result.setMessage("查看失败，请稍后再试");
            result.setCode(400);
        }
        return result;
    }

    /***
     * 增加/修改  角色
     * @param tradeSysRoleDto
     * @return
     */
    @Override
    @Transactional
    public Result inserRole(TradeSysRoleDto tradeSysRoleDto) {
        Result<Object> result = new Result<>();
            TradeSysRole role = new TradeSysRole();
            if (StringUtils.isEmpty(tradeSysRoleDto.getName())||StringUtils.isEmpty(tradeSysRoleDto.getMenuId())){
                result.setMessage("参数不能为空！");
                result.setCode(400);
                return result;
            }
           String name= tradeSysRoleMapper.selectByName(tradeSysRoleDto.getName());
            if (name!=null){
                result.setCode(400);
                result.setMessage("角色名已存在！");
                return result;
            }
            //增加角色
            String id = IdCreateUtil.getId();
            role.setId(id);
            role.setCreateTime(new Date());
            role.setUpdateTime(new Date());
            role.setSort(0);
            role.setName(tradeSysRoleDto.getName());
            role.setRemark(tradeSysRoleDto.getRemark());
            role.setState((byte) 1);
            tradeSysRoleMapper.insertSelective(role);
            //增加角色和菜单的关系
            TradeRoleMenu menu = new TradeRoleMenu();
            String[] s = tradeSysRoleDto.getMenuId().split("_");
            Date date = new Date();
            for (String s1 : s) {
                menu.setCreateTime(date);
                menu.setId(IdCreateUtil.getId());
                menu.setSysRoleId(id);
                menu.setSysMenuId(s1);
                tradeRoleMenuMapper.insertSelective(menu);
            }

        return result;
    }
    /**
     * 启用/禁用
     * @param tradeSysRoleDto
     * @return
     */
    @Override
    public Result updateRoleState(TradeSysRoleDto tradeSysRoleDto) {
        Result<Object> result = new Result<>();
        try {
            //查询最新状态
            TradeSysRole tradeSysRole = tradeSysRoleMapper.selectByPrimaryKey(tradeSysRoleDto.getId());
            if (tradeSysRole.getState()==1){
                tradeSysRoleMapper.updateRoleState(2,tradeSysRoleDto.getId());
            }else {
                tradeSysRoleMapper.updateRoleState(1,tradeSysRoleDto.getId());
            }

        }catch (Exception e){
            LOGGER.info("启用 禁用角色失败，失败信息为{}",tradeSysRoleDto);
            e.printStackTrace();
            result.setMessage("查看失败，请稍后再试");
            result.setCode(400);
        }

        return result;
    }

    /**
     *  根据用户id  查看是否勾选角色
     * @param tradeSysRoleDto
     * @return
     */
    @Override
    public Result selectRoleByUserId(TradeSysRoleDto tradeSysRoleDto) {
        Result<Object> result = new Result<>();
        try {
            if (tradeSysRoleDto.getId()!=null){
                //查询出用户对应的角色id
               List<String> list= tradeSysRoleMapper.selectIdsByUserId(tradeSysRoleDto.getId());
                List<TradeSysRoleVo> lists=tradeSysRoleMapper.selectQueryList(tradeSysRoleDto);
                if (lists!=null&& lists.size()>0){
                    for (TradeSysRoleVo roleVo : lists) {
                        if (list!=null &&list.contains(roleVo.getId())){
                            roleVo.setIsCheck(1);
                        }else {
                            roleVo.setIsCheck(2);
                        }
                    }
                }
                result.setData(lists);
            }else {
                //查询出所有角色
                List<TradeSysRoleVo> list=tradeSysRoleMapper.selectQueryList(tradeSysRoleDto);
                result.setData(list);
            }
        }catch (Exception e){
            LOGGER.info("查看是否勾选角色失败，失败信息为{}",tradeSysRoleDto);
            e.printStackTrace();
            result.setMessage("查看失败，请稍后再试");
            result.setCode(400);

        }
        return result;
    }

    /**
     * 更改角色关系
     * @param tradeSysRoleDto
     * @return
     */
    @Override
    @Transactional
    public Result updateRole(TradeSysRoleDto tradeSysRoleDto) {
        Result<Object> result = new Result<>();
            TradeSysRole role = new TradeSysRole();
            if (StringUtils.isEmpty(tradeSysRoleDto.getName())||StringUtils.isEmpty(tradeSysRoleDto.getMenuId())){
                result.setMessage("参数不能为空！");
                result.setCode(400);
                return result;
            }
            tradeRoleMenuMapper.deleteByRoleId(tradeSysRoleDto.getId());
            //更改角色
            role.setId(tradeSysRoleDto.getId());
            role.setUpdateTime(new Date());
            role.setName(tradeSysRoleDto.getName());
            role.setRemark(tradeSysRoleDto.getRemark());
            tradeSysRoleMapper.updateByPrimaryKeySelective(role);
            //增加角色和菜单的关系
            TradeRoleMenu menu = new TradeRoleMenu();
            String[] s = tradeSysRoleDto.getMenuId().split("_");
            Date date = new Date();
            for (String s1 : s) {
                menu.setCreateTime(date);
                menu.setId(IdCreateUtil.getId());
                menu.setSysRoleId(tradeSysRoleDto.getId());
                menu.setSysMenuId(s1);
                tradeRoleMenuMapper.insertSelective(menu);
            }
        return result;
    }

    @Override
    public void lunxunSimData() {
        SimpleDateFormat startTime = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        SimpleDateFormat endTime = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH,-1);
        Integer count=tradeRoleMenuMapper.selectCountData(startTime.format(instance.getTime()),endTime.format(instance.getTime()));
        if (count==null){
            count=0;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd");
        String format = dateFormat.format(instance.getTime());
        tradeRoleMenuMapper.insertIntoCount(count,format);
    }

}
